<template>
  <el-dialog
    top="10vh"
    width="500px"
    :close-on-click-modal="false"
    :modal="false"
    :title="step === 0 ? '导入库存' : '导入结果'"
    :visible="dialogFormVisible"
    center
    @close="reset"
  >
    <template v-if="step === 0">
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item
          label="经销商"
          prop="distributorId"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="form.distributorId"
            filterable
            remote
            placeholder="请选择经销商"
            :remote-method="DealerRemoteMethod"
            @change="getSupplierSelect"
            @focus="getgetSupplierSelect"
          >
            <el-option
              v-for="(item, index) in dealerOptions"
              :key="index"
              :label="item.companyName"
              :value="item.companyId"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="供应商"
          prop="supplierCode"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="form.supplierCode"
            filterable
            remote
            :disabled="!form.distributorId"
            placeholder="请选择供应商"
            :remote-method="SupplierRemoteMethod"
            @change="getProductLineSelect"
          >
            <el-option
              v-for="(item, index) in supplierOptions"
              :key="index"
              :label="item.vendorName"
              :value="item.vendorCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="产品线"
          prop="productLineCode"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="form.productLineCode"
            filterable
            remote
            :remote-method="ProductLineRemoteMethod"
            :disabled="!form.distributorId || !form.supplierCode"
            placeholder="请选择产品线"
          >
            <el-option
              v-for="(item, index) in productLineOptions"
              :key="index"
              :label="item.productLineName"
              :value="item.productLineCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上传" :label-width="formLabelWidth">
          <el-upload
            ref="upload"
            class="upload-demo"
            :http-request="upLoades"
            action="string"
            :on-change="handleUploadSuccess"
            accept=".xls,.xlsx"
            :file-list="fileList"
            :limit="2"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              支持.xls或.xlsx文件
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
    </template>
    <template v-else>
      <div class="center">
        <p>
          成功：
          <el-link type="success" :underline="false">{{
            result.successCount
          }}</el-link>
          条
        </p>
        <p>
          失败：<el-link type="danger" :underline="false">{{
            result.failureCount
          }}</el-link
          >条
        </p>
        <el-link
          v-if="result.failureCount === 0 ? false : true"
          style="color:#2371C5"
          @click="handleDonwLoad"
          >下载导入失败数据</el-link
        >
      </div>
    </template>
    <div slot="footer" class="dialog-footer">
      <el-button @click="reset">{{ step === 0 ? '取 消' : '完成' }}</el-button>
      <el-button type="primary" :disabled="isDisable" @click="onSubmit">{{
        step === 0 ? '下一步' : '继续导入'
      }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
// import dealerIM from '../../dealer-inventory-management'
import {
  dealerSelectDialog,
  getSupplier,
  productLineSelectDialog,
  uploadStock,
  noImportDealerInventory
} from '@api/m_mall_web_v1.js';
import { fileDownload } from '@const/utils';
import { fileUpload } from '@const/api.js';
import { $loadFileSimply } from '@const/loadFileOps';

export default {
  name: 'ImportInventory',
  // components:{dealerIM},
  data() {
    return {
      isDisable: false,
      fileList: [],
      uploadUrl: fileUpload,
      dialogFormVisible: false,
      step: 0,
      dealerOptions: [],
      supplierOptions: [],
      productLineOptions: [],
      form: {
        distributorId: '',
        distributorName: '',
        supplierCode: '',
        supplierName: '',
        productLineCode: '',
        productLineName: ''
      },
      companyId: '',
      file: null,
      rules: {
        distributorId: [
          { required: true, message: '请选择经销商', trigger: 'change' }
        ],
        supplierCode: [
          { required: true, message: '请选择供应商', trigger: 'change' }
        ],
        productLineCode: [
          { required: true, message: '请选择产品线', trigger: 'change' }
        ]
      },
      formLabelWidth: '120px',
      result: {
        successCount: 0,
        failureCount: 0,
        templateId: ''
      }
    };
  },
  methods: {
    upLoades() {},
    show() {
      this.dialogFormVisible = true;
      this.getDealerSelect();
    },
    handleUploadSuccess(file, fileList) {
      this.file = file;
      this.fileList = fileList;
      if (fileList.length > 1) {
        fileList.splice(0, 1);
      }
    },
    reset() {
      // this.step !== 0 || this.step == 0
      if (this.step !== 0) {
        this.$emit('done');
      }
      this.fileList = [];
      this.dialogFormVisible = false;
      this.step = 0;
      this.$refs.form && this.$refs.form.resetFields();
      this.$refs.SearchForm && this.SearchForm.resetFields();
      this.$refs.upload && this.$refs.upload.clearFiles();

      this.form = {
        distributorId: '',
        supplierCode: '',
        productLineCode: ''
      };
      this.result = {
        success: 0,
        fail: 0,
        templateId: ''
      };
      this.file = null;
    },
    onSubmit() {
      if (this.step === 0) {
        this.$refs.form.validate(valid => {
          if (valid) {
            this.handleSubmit();
          } else {

            console.log('error submit!!');
            return false;
          }
        });
      } else {
        // debugger
          this.SupplierRemoteMethod()
           this.ProductLineRemoteMethod()
        if(this.dealerOptions.length===0){
            this.form.distributorId=''
            this.form.supplierCode=''
            this.form.productLineCode=''
            
          }
        this.step = 0;
        this.fileList = [];
        this.file = null;
      }
    },
   getgetSupplierSelect(){
       this.DealerRemoteMethod()
     
   },
    async handleDonwLoad() {
      const result = await $loadFileSimply({
        method: 'post',
        url: noImportDealerInventory,
        params: {
          templateId: this.result.templateId
        }
      });
      fileDownload(result, '导入失败数据.xlsx');
    },
    async handleSubmit() {
      this.isDisable = true;
      setTimeout(() => {
        this.isDisable = false; // 点击一次时隔两秒后才能再次点击
      }, 2000);
      const fd = new FormData();

      if (this.file) {
        fd.append('file', this.fileList[0].raw);
      } else {
        this.$message.error('请上传文件');
        return;
      }

      const params = {
        distributorId: '',
        distributorName: '',
        supplierCode: '',
        supplierName: '',
        productLineCode: '',
        productLineName: ''
      };
      // 经销商
      params.distributorId = this.form.distributorId;
      const dealerItem = this.dealerOptions.find(
        item => item.companyId === this.form.distributorId
      );
      if (dealerItem) {
        params.distributorName = dealerItem.companyName;
      }

      // 供应商
      params.supplierCode = this.form.supplierCode;
      const supplierItem = this.supplierOptions.find(
        item => item.vendorCode === this.form.supplierCode
      );
      if (supplierItem) {
        params.supplierName = supplierItem.vendorName;
      }
      // 产品线
      params.productLineCode = this.form.productLineCode;
      const productLineItem = this.productLineOptions.find(
        item => item.productLineCode === this.form.productLineCode
      );
      if (productLineItem) {
        params.productLineName = productLineItem.productLineName;
      }

      const result = await this.$axios({
        method: 'post',
        url: uploadStock,
        headers: { 'Content-Type': 'multipart/form-data' },
        params,
        data: fd
      });

      if (result.status === 200) {
        this.step = 1;
        this.result = result.data.payload;

        //   if (this.step !== 0) {
        this.$emit('done');
        // }
      } else {
        this.$message.error(result.data.payload);
      }
    },

    DealerRemoteMethod(val) {
      
      this.loading = true;
      const query = {
        companyName: val
      };
      this.$axios
        .$post(dealerSelectDialog, query)
        .then(res => {

          this.dealerOptions = res.payload;
          this.loading = false;

        })
        .then(() => {});
    },
    async getDealerSelect() {
      // 经销商
      const result = await this.$axios({
        method: 'post',
        url: dealerSelectDialog,
        data: {}
      });
      if (result.status === 200) {
        const { data } = result;
        this.dealerOptions = data.payload;
      }
    },

    SupplierRemoteMethod(val) {
      this.loading = true;
      const query = {
        distributorId: this.form.distributorId,
        busModel: '1',
        supplierName: val
      };
      this.$axios.$post(getSupplier, query).then(res => {
        this.supplierOptions = res.payload.content;
        this.loading = false;
      });
    },

    async getSupplierSelect() {
      // 供应商
      this.form.supplierCode = null;
      this.form.productLineCode = null;
      const result = await this.$axios({
        method: 'post',
        url: getSupplier,
        data: {
          distributorId: this.form.distributorId,
          supplierName: '',
          busModel: '1'
        }
      });
      if (result.status === 200) {
        const { data } = result;
        this.supplierOptions = data.payload.content;
      }
    },

    ProductLineRemoteMethod(val) {
      this.loading = true;
      const query = {
        companyId: this.form.distributorId,
        productLineName: val,
        supplierCode: this.form.supplierCode
      };
      this.$axios.$post(productLineSelectDialog, query).then(res => {
        this.productLineOptions = res.payload;
        this.loading = false;
      });
    },

    async getProductLineSelect() {
      // 产品线
      this.form.productLineCode = '';
      const result = await this.$axios({
        method: 'post',
        url: productLineSelectDialog,
        data: {
          companyId: this.form.distributorId,
          productLineName: '',
          supplierCode: this.form.supplierCode
        }
      });
      if (result.status === 200) {
        const { data } = result;
        this.productLineOptions = data.payload;
      }
    }
  }
};
</script>

<style lang="less">
.center {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  p {
    margin-bottom: 20px;
  }
}
</style>
